<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/22
 * Time: 14:50
 */

namespace app\api\model;
use app\common\lib\exception\ApiException;
use think\Model;
use think\Log;
use think\Db;
use app\admin\model\Lesson as LessonModel;

class Lesson extends Model
{
    /**
     * 通过课程编号或者课程id获取课程信息
     * @param string lesson_sn 课程编号 *必传
     * @param user_id int 选传 用户id
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function getLessonByIdOrCode($data){

        //判断是否传递课程审核参数，默认查看已审核！
        if(!isset($data['is_approve'])){
            $data['is_approve'] = 1;
        }

        $where = 'le.is_approve='.$data['is_approve'].' AND (le.lesson_sn='.$data['lesson_sn'].' OR le.id='.$data['lesson_sn'].')';

        $info = $this
            ->alias('le')
            ->join('city c','le.city_id = c.id','LEFT')
            ->join('subject s','le.subject_id = s.id','LEFT')
            ->join('lesson_program p','le.program_id = p.id','LEFT')
            ->join('user user','le.teacher_id = user.id','LEFT')
            ->join('classroom cla','le.classroom_id = cla.id','LEFT')
            ->join('service_target tar','le.service_target_id = tar.id','LEFT')
            ->join('class css','le.class_id = css.id','LEFT')
            ->join('lesson_nature na','le.lesson_nature_id = na.id','LEFT')
            ->join('start_lesson sle','le.start_lesson_id = sle.id','LEFT')
            ->where($where)
            ->field('le.id,le.city_id,le.teacher_id,c.name,le.subject_id,s.subject,le.program_id,p.program_full_name,p.program,le.lesson_name,tar.service_target,css.class_type,le.class_id,le.classroom_id,le.service_target_id,le.lesson_nature_id,le.start_lesson_id,na.lesson_nature,lesson_start_time,le.lesson_sn,le.lesson_cost,le.max_person,le.classroom_description,le.teacher_description,le.lesson_num,le.lesson_method,le.one_lesson_time,le.lesson_status,le.teacher_group_images,le.teacher_group_description,le.lesson_feature,le.adapt_crowd,le.add_description,le.com_lesson_num,le.registration_end_time,le.lesson_time_description,le.is_approve,le.teacher_id,user.full_name as teacher_name,cla.classroom_address,le.cost_type,le.is_comment,le.is_reclass,le.cost_type_description,le.lesson_cost_old,le.grade_id,le.start_lesson_id')
            ->find();

        if($info){
            $info = $info->toArray();
            if(!empty($info['teacher_group_images'])){
                $info['teacher_group_images'] = json_decode(htmlspecialchars_decode($info['teacher_group_images']));
            }

            if(!empty($info['grade_id'])){
                $info['grade_name'] = Db::name('grade')->where('id','in',$info['grade_id'])->column('grade');
                $info['grade_name'] = implode('，',$info['grade_name']);
            }

            if(!empty($data['user_id'])){

                $order = Db::name('order')
                    ->where('(order_lesson_sn='.$data['lesson_sn'].' OR lesson_id='.$data['lesson_sn'].') AND user_id='.$data['user_id'])
                    /*->where('order_lesson_sn',$data['lesson_sn'])
                    ->whereOr('lesson_id',$data['lesson_sn'])
                    ->where('child_id',$data['child_id'])*/
                    ->field('id')
                    ->find();
                //return show(config('code.success'),'ok！',$order);
                if(!empty($order)){
                    $info['order_status'] = 1;
                }else{
                    $info['order_status'] = 0;
                }
            }
        }

        return $info;
    }

    /**
     * 根据课程id获取课程信息
     * @param int $lesson_id 课程id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function getLessonByLessonId($lesson_id){
        $lesson = $this->where('id='.$lesson_id)
            ->field('lesson_sn,lesson_name,lesson_cost,max_person,registration_end_time,is_approve,cost_type')
            ->find();
        return $lesson;
    }

    /**
     * 获取班级类型
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function classType(){
        try{
            $info = Db::name('class')->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
    /**
     * @获取课程科目
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function subject(){
        try{
            $info = Db::name('subject') ->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
    /**
     * @获取课程项目
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function lessonProgram(){
        $data = $_POST;
        if(empty($data)){
            throw new ApiException('数据不合法',404);
        }
        //subject_id 必传 课程科目id
        if(empty($data['subject_id'])){
            throw new ApiException('subject_id is not found',404);
        }
        try{
            $programs = Db::name( 'lesson_program' )->where ( array ('subject_id' => $data['subject_id'] ) )->select ();

            return show(config('code.success'),'获取数据成功',$programs,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * @获取课程服务目标
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function serviceTarget(){
        try{

            $info = Db::name('service_target')->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
    /**
     * @获取 课程课程风格
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function lessonNature(){
        try{
            $info = Db::name('lesson_nature')->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
    /**
     * @获取 获取课程的开课时间
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function startLesson(){ //lesson控制器 get_start_lesson
        try{
            $info = Db::name('start_lesson')->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
    /**
     * @获取 年级
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function grade(){
        try{
            $info = Db::name('grade')->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }
    /**
     * 教师课程发布
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function addLesson(){

        if(empty($_POST)){
            throw new ApiException('数据不合法',404);
        }

        try{

            $_POST = special_str($_POST);

//            $validate = new Lesson();
//            if(!$validate->check($_POST)){
//                return show(config('code.error'),$validate->getError(),[],400);
//            }

            //图片处理
            if(!empty($_FILES)){
                $image = uploadImage("teacher_group_images");
                if(is_object($image)){
                    return $image;
                }
                $_POST['teacher_group_images']= $image;
            }
            //return $_POST;
            //$_POST['grade_id'] = implode(',',$_POST['grade_id']);

             $grade_id = json_decode($_POST['grade_id']);
             $_POST['grade_id'] = implode(',',$grade_id);

            if(!empty($_POST['registration_end_time'])){
                $_POST['registration_end_time'] = strtotime($_POST['registration_end_time']);
            }else{
                $_POST['registration_end_time'] = '';
            }
            $teacher = Db::name('user')->where('id',$_POST['teacher_id'])->find();

            $tel = $teacher['tel'];
            $teacher_lesson = Db::name('lesson')->where('teacher_id',$_POST['teacher_id'])->select();
            $arr = [];
            if($teacher_lesson){
                foreach($teacher_lesson as $k => $v){
                    $arr[]=substr($teacher_lesson[$k]['lesson_sn'],0,4);
                }
                $_POST['lesson_sn'] = sprintf("%04d",max($arr)+1).$tel;
            }else{
                $_POST['lesson_sn'] = sprintf("%04d",1) . $tel;//制作的课程代码
            }

            //合作者
            if(!isset($_POST['cooperate_user'])){
                $_POST['cooperate_user'] = 1;
            }

            //halt($_POST);
            $rec = Db::name('lesson')->insertGetId($_POST);
            if($rec){

                // 修改教室的使用状态
                $classroom = Db::name("classroom")->where('id',$_POST['classroom_id'])->find();
                if(!empty($classroom['lesson_id'])){
                    $lesson_id = $classroom['lesson_id'].','.$rec;
                }else{
                    $lesson_id = $rec;
                }
                Db::name('classroom')
                    ->where('id', $_POST['classroom_id'])
                    ->update([
                        'status' => '1',
                        'lesson_id'=>$lesson_id
                    ]);

                $lesson_num = $_POST['lesson_num'];
                $result = [];
                for($i=1;$i<=$lesson_num;$i++){
                    $data['lesson_id'] = $rec;
                    $data['lesson_number'] = $i;
                    $data['lesson_start_time'] = '0';
                    $data['lesson_end_time'] = '0';
                    $result[]= Db::name('lesson_num_time')->insertGetId($data);
                }

                if(count($result) == $lesson_num){
                    return show(config('code.success'),'新增课程成功');
                }

            }else{
                return show(config('code.error'),'新增课程失败');
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }
    /**
     * 编辑课程信息
     * @param id int 必传字段
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function editLesson(){

        if(empty($_POST)){
            throw new ApiException('数据不合法',404);
        }
        // 课程id 必传 int
        if(empty($_POST['id'])){
            throw new ApiException('id is not found',404);
        }

        try{
            $_POST = special_str($_POST);// 过滤字段中所包含的特殊字符

            $lesson = $this->where('id',$_POST['id'])->find()->toArray();

            if($lesson['is_approve'] == 1){
                return show(config('code.error'),'当前课程已审核，不可修改。');
            }

//            $validate = new Lesson();
//            if(!$validate->check($_POST)){
//                return show(config('code.error'),$validate->getError());
//            }


            //图片处理
            if(!empty($_FILES)){
                $image = uploadImage("teacher_group_images");
                if(is_object($image)){
                    return $image;
                }
                $_POST['teacher_group_images'] = $image;
            }else{
                //修改时未上传则删除空数据
                unset($_POST['teacher_group_images']);
            }

            // 课时更新
            if(!empty($_POST['lesson_num']) && $_POST['lesson_num'] != $lesson['lesson_num']){
                $sum = $lesson['lesson_num'];// 当前该课程的课时数
                $result = [];
                if($_POST['lesson_num'] > $lesson['lesson_num']){ //课时增加
                    for($i=$sum+1;$i<=$_POST['lesson_num'];$i++){
                        $data['lesson_id'] = $_POST['id'];
                        $data['lesson_number'] = $i;
                        $result[]=Db::name('lesson_num_time')->insertGetId($data);
                    }
                    if(count($result) != abs($_POST['lesson_num']-$lesson['lesson_num'])){
                        return show(config('code.error'),'课时更新失败');
                    }
                }elseif(($_POST['lesson_num'] < $lesson['lesson_num'])){ // 课时减少
                    for($i=$sum;$i>$_POST['lesson_num'];$i--){
                        $result[] = Db::name('lesson_num_time')
                            ->where('lesson_number',$i)
                            ->where('lesson_id',$_POST['id'])
                            ->delete();
                    }
                    if(count($result) != abs($_POST['lesson_num']-$lesson['lesson_num'])){
                        return show(config('code.error'),'课时更新失败');
                    }
                }
            }else{

            }

            //$grade_id = $_POST['grade_id'];
            $grade_id = json_decode($_POST['grade_id']);
            $_POST['grade_id'] = implode(',',$grade_id);

            //课程报名截止日期
            if(!empty($_POST['registration_end_time'])){
                $_POST['registration_end_time'] = strtotime($_POST['registration_end_time']);
            }
            // 课程代码
            if($_POST['teacher_id'] == $lesson['teacher_id']){

            }elseif($_POST['teacher_id'] != $lesson['teacher_id']){
                $te_info = Db::name('user')->where(array('id' => $_POST['teacher_id']))->find();//根据所接收的教师id获取教师电话，制作课程代号
                $tel = $te_info['tel'];
                // 查询所更换上课的教师是否有发布课程
                $teacher_lesson=Db::name('lesson')->where('teacher_id',$_POST['teacher_id'])->select();
                $arr = [];
                if($teacher_lesson){ //有发布课程  使自己的课程流水+1
                    foreach($teacher_lesson as $k => $v){
                        $arr[]=substr($teacher_lesson[$k]['lesson_sn'],0,4);
                    }
                    $_POST['lesson_sn'] = sprintf("%04d",max($arr)+1).$tel;
                }else{ //没有发布课程  使自己的课程流水为0001
                    $_POST['lesson_sn'] = sprintf("%04d",1) . $tel;//制作的课程代码
                }
            }

            /*$rec = */$this->allowField(true)->where('id',$_POST['id'])->update($_POST);

            //if($rec){

                //修改教室
                if($lesson['classroom_id'] != $_POST['classroom_id']){
                    //获取编辑之前教室id
                    $classroom_id =  $lesson['classroom_id'];
                    //更换教室之前 在当前教室记录中删掉被lesson_id占用的lesson_id
                    $classroom = Db::name("classroom")->where('id',$lesson['classroom_id'])->find();

                    //当前教室只有一个课程使用
                    if(strlen(trim($classroom['lesson_id'])) == 1){
                        Db::name('classroom')
                            ->where('id', $classroom_id)
                            ->update([
                                'status' => '0',
                                'lesson_id'=>''
                            ]);

                    }elseif(strlen(trim($classroom['lesson_id'])) > 1){
                        $arr_classroom = explode(',',$classroom['lesson_id']);
                        $key = array_search($lesson['id'],$arr_classroom);
                        unset($arr_classroom[$key]);
                        $lesson = implode(',',$arr_classroom);

                        Db::name('classroom')
                            ->where('id', $classroom_id)
                            ->update([
                                'lesson_id'=>$lesson
                            ]);

                    }

                    // 编辑修改教室的使用状态和教室使用对象
                    $classroom = Db::name("classroom")->where('id',$_POST['classroom_id'])->find();
                    if(!empty($classroom['lesson_id'])){
                        $lesson_id = $classroom['lesson_id'].','.$_POST['id'];
                    }else{
                        $lesson_id = $_POST['id'];
                    }
                    Db::name('classroom')
                        ->where('id', $_POST['classroom_id'])
                        ->update([
                            'status' => '1',
                            'lesson_id'=>$lesson_id
                        ]);
                }

            if(!empty($_FILES)) {
                if (!empty($lesson['teacher_group_images'])) {
                    delImages(json_decode(htmlspecialchars_decode($lesson['teacher_group_images'])));
                    //检查父级目录是否为空并删除空目录
                    checkFileParentDir(json_decode(htmlspecialchars_decode($lesson['teacher_group_images'])));
                }
            }

            return show(config('code.success'),'编辑成功');
            /*}else{
                return show(config('code.error'),'编辑失败');
            }*/

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(), 500);
        }
    }

    /**
     * 通过id或者课程代码查询课程详情信息
     * @param lesson_sn int 课程id或者课程代码 *必传
     * @param is_approve int 是否审核 0待审核 1已审核 2已开课 默认为1
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function lessonDetails(){
        $data = $_GET;

        if(empty($data)) {
            throw new ApiException('数据不合法！',401);
        }

        if(!isset($data['lesson_sn'])) {
            throw new ApiException('lesson_sn is not found！',404);
        }

        try{
            $lesson = $this->getLessonByIdOrCode($data);

            return show(config('code.success'),'获取课程信息成功！',$lesson);

        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(), 400);
        }
    }

    /**
     * 根据年级查询课程信息
     * @param grade_id int 年级id *必传
     * @param user_id int 当前用户 选传
     * @param cost_type int 费用类型 1学费 2学币 *必传
     * @param page int 获取数据页码 不传默认为第一页
     * @param count int 每页显示条数不传默认为6条
     * @param is_approve int 是否审核 0待审核 1已审核 2已开课 默认为1
     * @param com_lesson_num int 完结课时数 不传默认为0 (未开课)
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function findLesson(){
        $data = $_POST;

        if(empty($data)) {
            throw new ApiException('数据不合法',404);
        }

        //年级id必须传递
        if(!isset($data['grade_id'])){
            throw new ApiException('grade_id is not found',404);
        }

        //费用类型必须传递
        if(!isset($data['cost_type'])){
            throw new ApiException('cost_type is not found',404);
        }

        //获取数据页码 不传默认为第一页
        if(!isset($data['page'])){
            $data['page'] = 1;
        }

        //是否审核 0待审核 1已审核 2已开课 默认为1
        if(!isset($data['is_approve'])){
            $data['is_approve'] = 1;
        }

        //完结课时数 不传默认为0 (未开课)
        if(!isset($data['com_lesson_num'])){
            $data['com_lesson_num'] = 0;
        }

        //每页显示条数不传默认为6条
        if(!isset($data['count'])){
            $data['count'] = 6;
        }

        try{
            $les_arr = db('lesson')
                ->alias('le')
                ->join('subject ', 'le.subject_id=subject.id', 'LEFT')
                ->join('lesson_program ', 'le.program_id=lesson_program.id', 'LEFT')
                ->field('le.id as lessonid,le.lesson_sn,le.grade_id,le.lesson_cost,subject.subject,lesson_program.program,le.lesson_name')
                ->where('le.cost_type="'.$data['cost_type'].'" AND le.is_approve="'.$data['is_approve'].'" AND le.com_lesson_num="'.$data['com_lesson_num'].'"')
                ->field('le.id,le.grade_id')
                ->select();

            $ids = [];
            foreach ($les_arr as $key => $val){
                if(in_array($data['grade_id'],explode(',',$val['grade_id']))){
                    $ids[$key] = $val['id'];
                }

            }

            $les_str = implode(',',$ids);

            $lesson_info = db('lesson')
                ->alias('le')
                ->join('subject ', 'le.subject_id=subject.id', 'LEFT')
                ->join('lesson_program ', 'le.program_id=lesson_program.id', 'LEFT')
                ->field('le.id as lessonid,le.lesson_sn,le.grade_id,le.lesson_cost,subject.subject,lesson_program.program,le.lesson_name')
                ->where('le.id','in',$les_str)
                ->paginate(6);

            return $lesson_info;

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }

      /*  //获取数据页码 不传默认为第一页
        if(!isset($data['page'])){
            $data['page'] = 1;
        }

        //是否审核 0待审核 1已审核 2已开课 默认为1
        if(!isset($data['is_approve'])){
            $data['is_approve'] = 1;
        }

        //完结课时数 不传默认为0 (未开课)
        if(!isset($data['com_lesson_num'])){
            $data['com_lesson_num'] = 0;
        }

        //每页显示条数不传默认为6条
        if(!isset($data['count'])){
            $data['count'] = 6;
        }

        //根据参数返回数据
        try{
            $lesson_details = Db::name('lesson')
                ->alias('le')
                ->join('subject ', 'le.subject_id=subject.id', 'LEFT')
                ->join('lesson_program ', 'le.program_id=lesson_program.id', 'LEFT')
                ->field('le.id as lessonid,le.lesson_sn,le.grade_id,le.lesson_cost,subject.subject,lesson_program.program')
                ->where('le.cost_type="'.$data['cost_type'].'" AND le.is_approve="'.$data['is_approve'].'" AND le.com_lesson_num="'.$data['com_lesson_num'].'"')
                ->select();

            foreach ($lesson_details as $key => $val) {
                $val['grade_arr'] = explode(',', $val['grade_id']);

                if (in_array($data['grade_id'], $val['grade_arr'])) {
                    $lesson[$key] = $val;

                    $lessons[] = Db::name('lesson')
                        ->alias('le')
                        ->join('subject', 'le.subject_id=subject.id', 'LEFT')
                        ->join('lesson_program', 'le.program_id=lesson_program.id', 'LEFT')
                        ->field('le.id as lessonid,le.lesson_sn,le.grade_id,le.lesson_cost,le.lesson_name')
                        ->where('le.id="'.$val['lessonid'].'" AND le.cost_type="'.$data['cost_type'].'" AND le.is_approve="'.$data['is_approve'].'" AND le.com_lesson_num="'.$data['com_lesson_num'].'"')
                        ->select();
                    $pagedata = [];
                    foreach ($lessons as $k => $v) {
                        $start = ($data['page'] - 1) * $data['count']; //计算每次分页的开始位置
                        $totals = count($lessons);
                        $countpage = ceil($totals / $data['count']); //计算总页面数
                        $pagedata = array_slice($lessons, $start, $data['count']);
                    }
                }
            }

            if(!empty($pagedata)){
                return show(config('code.success'),'获取课程信息成功！',$pagedata);
            }else{
                return show(config('code.success'),'没有相关的课程信息！',[]);
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }*/

    }
}